<!--
  模块：问卷调查 - 首页
-->
<template>
  <div class="question">
    <!-- 过滤搜索 -->
    <QuestionHeader @condition-query="conditionQuery" @reset="reset" />

    <AppMainContent>
      <el-table v-loading="loading" :data="questionList">
        <el-table-column label="" align="center" width="60" type="selection" />
        <el-table-column label="序号" align="center" width="100" type="index" />
        <el-table-column
          label="问卷标题"
          align="left"
          prop="title"
          min-width="20%"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="开启时间"
          align="center"
          prop="startTime"
          min-width="13%"
        />
        <el-table-column
          label="截止时间"
          align="center"
          prop="endTime"
          min-width="13%"
        />
        <el-table-column
          label="发布人"
          align="center"
          prop="publishUserName"
          min-width="7%"
        />
        <el-table-column
          label="发布日期"
          align="center"
          prop="publishTime"
          min-width="7%"
        />
        <el-table-column label="状态" align="center" min-width="10%">
          <template slot-scope="scope">
            {{ getStatus(scope.row.status, scope.row.close) }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          min-width="15%"
          class-name="small-padding fixed-width"
          class="btn"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="fetchQuestion(scope.row.id)"
            >
              详情
            </el-button>
            <el-button
              size="mini"
              type="text"
              :disabled="scope.row.close !== 2 ? true : false"
              @click="editQuestion(scope.row.id)"
            >
              修改
            </el-button>
            <el-button
              size="mini"
              type="text"
              :disabled="scope.row.close !== 1 ? true : false"
              @click="closeQuestion(scope.row)"
            >
              关闭
            </el-button>
            <el-button
              size="mini"
              type="text"
              :disabled="scope.row.close !== 0 ? true : false"
              @click="statisticQuestion(scope.row.id)"
            >
              统计
            </el-button>
            <!-- <el-button
              size="mini"
              type="text"
              :disabled="scope.row.close === 1 ? true : false"
              @click="exportQuestion(scope.row.id)"
            >
              导出
            </el-button> -->
            <el-button
              size="mini"
              type="text"
              :disabled="scope.row.close === 1 ? true : false"
              @click="delQuestion(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <Pagination
        v-show="total > 0"
        :total="total"
        :current.sync="queryParams.pageNum"
        :size.sync="queryParams.pageSize"
        @pagination="getList(queryParams.pageNum)"
      />
    </AppMainContent>

    <router-view />
  </div>
</template>

<script>
import request from '@/utils/request'
import QuestionHeader from '@/views/question/components/question-header/index.vue'
//引入 coment 组件
import moment from 'moment'
//引入的请求
import {
  pageQuestion,
  updateQuestion,
  updateCloseQuestion,
  deleteQuestion,
  exportQuestion,
} from '@/api/question/index.js'

//todo 按钮
export default {
  inject: ['reload'],
  name: 'Question',
  components: {
    QuestionHeader,
  },
  watch: {
    '$route.query.msg'(newRoute, oldRoute) {
      if (newRoute !== undefined) {
        this.reload()
      }
      console.log(newRoute, 'newRoute')
      console.log(oldRoute, 'oldRoute')
    },
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 供需超市表格数据
      questionList: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        type: undefined,
      },
      // 总条数
      total: 0,
      //判断是否能被修改
      isShowEdite: false,
      //判断是否已经删除
      isShowDel: false,
      test1: 'hi',
    }
  },
  beforeMount() {
    /** 查询问卷列表 */
    this.getList(1)
  },
  methods: {
    //! 导出问卷
    exportQuestion(id) {
      exportQuestion(id)
        .then((resp) => {
          if (resp) {
            let blob = new Blob([resp])
            let url = window.URL.createObjectURL(blob)
            let link = document.createElement('a')
            link.href = url
            link.download = item.fileName || '下载文件' //下载后文件名
            document.body.appendChild(link)
            link.click() //点击下载
            link.remove() //下载完成移除元素
            window.URL.revokeObjectURL(link.href) //用完之后使用URL.revokeObjectURL()释放；
          } else {
            Message.error('文件下载失败，请重试！')
          }
        })
        .catch((e) => {
          Message.error('暂无下载该文件的权限！')
        })
        .finally(() => {
          //请求结束回调
        })
    },

    //! 统计问卷
    statisticQuestion(id) {
      console.log(id, 'statisticQuestion')
      this.$router.push({
        path: '/question/questionStatistic',
        query: {
          id: id,
        },
      })
    },

    //! 修改问卷的方法
    editQuestion(id) {
      console.log(id, 'editQuestion')
      this.$router.push({
        path: '/question/questionEdit',
        query: {
          id: id,
        },
      })
    },

    //! 删除问卷 方法
    delQuestion(id) {
      this.$confirm(`确认删除本问卷吗`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deleteQuestion(id).then((res) => {
          console.log(res)
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'success',
          })
          this.getList(1)
        })
      })
    },

    //! 关闭问卷方法
    closeQuestion(question) {
      console.log(question, 'closeQuestion')
      this.$confirm(`确认关闭本问卷吗`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        updateCloseQuestion(question.id).then((res) => {
          console.log(res)
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'success',
          })
          this.getList(1)
        })
      })
    },

    //! 重置搜索结果
    reset() {
      this.getList(1)
    },

    //! 条件查询出来的结果
    conditionQuery(data) {
      this.loading = true
      this.questionList = data.list
      this.isClose()
      this.total = data.total
      this.loading = false
    },

    //! 查询问卷详情
    fetchQuestion(id) {
      console.log(id, 'fetchQuestion')
      console.log(this.$router, 'fetchQuestion')
      this.$router.push({
        path: '/question/questionDetail',
        query: {
          id: id,
        },
      })
    },

    //! 查询问卷列表
    getList(current) {
      this.loading = true
      pageQuestion({ current: current }).then((res) => {
        console.log(res)
        this.questionList = res.data.list
        this.isClose()
        this.total = res.data.total
        this.loading = false
      })
    },

    //! 判断是否开启问卷了,如果到了开启问卷时间更新数据库，或者到了关闭问卷的时间更新问卷
    isClose() {
      console.log(this.questionList)
      if (this.questionList !== null) {
        this.questionList.forEach((item, index) => {
          //* 不是保存状态
          if (this.questionList[index].status !== 1) {
            //* 不是关闭状态
            if (this.questionList[index].close !== 0) {
              //* 待开启状态
              if (this.questionList[index].close === 2) {
                if (
                  this.questionList[index].startTime <
                    moment(new Date()).format('YYYY-MM-DD HH:mm:ss') &&
                  this.questionList[index].endTime >
                    moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
                ) {
                  this.questionList[index].close = 1
                  updateQuestion(this.questionList[index]).then((res) => {
                    console.log(res)
                  })
                }
                //* 已开启状态
              } else if (
                this.questionList[index].endTime <
                moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
              ) {
                this.questionList[index].close = 0
                updateQuestion(this.questionList[index]).then((res) => {
                  console.log(res)
                })
              }
            }
          }
        })
      }
    },

    //! 显示问卷的状态
    getStatus(status, close) {
      let mapSatus = ''

      if (status === 1) {
        mapSatus = '已保存'
      } else if (status === 2) {
        if (close === 2) {
          mapSatus = '待开启'
        } else if (close === 1) {
          mapSatus = '已开启'
        } else {
          mapSatus = '已关闭'
        }
      }

      return mapSatus
    },
  },
}
</script>

